<!-- 进程管控 -->
<template>
  <div>
    <el-row>
      <div style="display:flex;justify-content:space-between;">
        <div>
          <el-button type="primary" @click="add">添加移动存储介质</el-button>
          <!-- <span style="color:red;font-size:14px;padding-left:20px;">运行信任的签名证书程序，将不会上送检测，也不会进行进程阻断</span> -->
        </div>
      </div>
      <el-table stripe border :data="tableData" row-key="Name" style="width: 100%; margin-top: 15px">
        <el-table-column label="序号" width="60" type="index"
          :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
        <el-table-column label="名称" prop="Name" show-overflow-tooltip></el-table-column>
        <el-table-column label="移动存储介质序列号" prop="Sn" show-overflow-tooltip></el-table-column>
        <el-table-column label="厂商ID" prop="VID" show-overflow-tooltip></el-table-column>
        <el-table-column label="产品ID" prop="PID" show-overflow-tooltip></el-table-column>
        <el-table-column label="登记时间" prop="TansTime" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.TansTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="登记人员" prop="RegUser" show-overflow-tooltip></el-table-column>
        <el-table-column label="备注信息" prop="Descp" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" fixed="right" width="160px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="editTableItem(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="danger" :disabled="scope.row.Sn === defaultSn" @click="deleteOnclick(scope.row, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="添加移动存储介质" :visible.sync="auditdialog"
      v-el-drag-dialog width="1000px" @close="onFormClose">
      <el-form label-width="150px" :model="auditForm" :rules="rules" ref="auditForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">基本规则内容</el-divider>
          <el-form-item label='名称：' prop="Name">
            <el-input v-model="auditForm.Name" placeholder="请输入名称" :maxlength="30" :disabled="editIndex >= 0"></el-input>
          </el-form-item>
          <el-form-item label='类型：' prop="Type">
            <el-select style="width:100%" v-model="auditForm.Type" filterable allow-create placeholder="请选择类型" :disabled="editIndex >= 0">
              <el-option v-for="(item, index) in OBJList" :key="index" :label="item.Name" :value="item.Value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label='存储介质：' prop="UsbDevice">
            <el-select style="width:100%" v-model="auditForm.UsbDevice" @change="UsbDeviceChange" filterable allow-create
              placeholder="请选择存储介质" :disabled="editIndex >= 0">
              <el-option v-for="(item, index) in filterUsbDeviceList" :key="index" :label="item.DisplayName"
                :value="item.DisplayName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label='存储介质序列号：' prop="Sn">
            <el-input v-model="auditForm.Sn" placeholder="请输入存储介质序列号" maxlength="50" :disabled="editIndex >= 0"></el-input>
          </el-form-item>
          <el-form-item label='厂商ID：' prop="VID">
            <el-input v-model="auditForm.VID" placeholder="请输入厂商ID" maxlength="50" :disabled="editIndex >= 0"></el-input>
          </el-form-item>
          <el-form-item label='产品ID：' prop="PID">
            <el-input v-model="auditForm.PID" placeholder="请输入产品ID" maxlength="50" :disabled="editIndex >= 0"></el-input>
          </el-form-item>
          <el-form-item label='登记人员：' prop="RegUser">
            <el-input v-model="auditForm.RegUser" placeholder="请输入登记人员" maxlength="50"></el-input>
          </el-form-item>
          <el-form-item label='备注信息：' prop="Descp">
            <el-input v-model="auditForm.Descp" maxlength="50" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="auditdialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import { parseTime } from '@/utils/index'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  data() {
    return {
      editIndex: -1,

      defaultSn: '6A00D9A1C7B4F283',

      pageNum: 1,
      pageSize: 10,
      tableData: [],
      auditForm: {},
      auditdialog: false,
      OBJList: [
        { Name: 'USB存储介质', Value: 1 },
        // { Name: '手机', Value: 2 },
      ],
      UsbDeviceList: [],
      rules: {
        Name: [
          { required: true, message: "请输入名称" }
        ],
        Type: [
          { required: true, message: "请选择类型", trigger: 'change' }
        ],
        UsbDevice: [
          { required: true, message: "请选择存储介质", trigger: 'change' }
        ],
        Sn: [
          { required: true, message: "请输入存储介质序列号" }
        ],
        VID: [
          { required: true, message: "请输入厂商ID" }
        ],
        PID: [
          { required: true, message: "请输入产品ID" }
        ],
      },
    }
  },
  computed: {
    deviceCompareObj () {
      const obj = {}

      this.tableData.forEach(item => {
        obj[`${item.Sn}_${item.VID}_${item.PID}`] = true
      })

      return obj
    },
    filterUsbDeviceList () {
      return this.UsbDeviceList.filter(item => !this.deviceCompareObj[`${item.Sn}_${item.Vid}_${item.Pid}`])
    }
  },
  watch: {

  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    parseTime,
    async getData() {
      const data = {
        Filter: {
          FileName: 'param_reg_usb.json'
        }
      }
      const res = await connrequest('GetUICommonParam', data)
      this.tableData = res.Data
    },
    async add() {
      this.auditForm = {
        Type: 1
      }
      await this.GetUsbDeviceList()
      this.auditdialog = true
      this.$nextTick(() => {
        this.$refs.auditForm.clearValidate();
      })
    },
    editTableItem (row, index) {
      this.editIndex = index

      this.auditForm = {
        ...row
      }
      
      this.auditdialog = true
    },
    async GetUsbDeviceList() {
      const res = await connrequest('GetUsbDeviceList')
      this.UsbDeviceList = res.Data
    },
    UsbDeviceChange(value) {
      const row = this.UsbDeviceList.find(item => item.DisplayName == value) || {}
      this.$set(this.auditForm, 'Sn', row.Sn)
      this.$set(this.auditForm, 'VID', row.Vid)
      this.$set(this.auditForm, 'PID', row.Pid)
    },
    async submit() {
      this.$refs.auditForm.validate(async (valid) => {
        if (valid) {

          // 修改
          if (this.editIndex >= 0) {
            this.putTableItemApi()

            return
          }

          // 检查是否有重复项
          this.tableData = this.tableData || []
          const isDuplicate = this.tableData.some(item =>
            item.PID === this.auditForm.PID &&
            item.VID === this.auditForm.VID &&
            item.Sn === this.auditForm.Sn
          ) || false;
          if (isDuplicate) {
            this.$message({
              type: 'warning',
              message: '该移动存储介质已存在，无法重复添加！'
            });
            return; // 阻止提交
          }
          // 如果没有重复，则继续提交
          const data = {
            Filter: {
              FileName: 'param_reg_usb.json'
            },
            Data: [
              ...this.tableData,
              {
                ...this.auditForm,
                TansTime: Math.floor(Date.now() / 1000)
              }
            ]
          };
          const res = await connrequest('SetUICommonParam', data);
          if (res.Status.StatusCode === 0) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.getData();
          }
          this.auditdialog = false;
        } else {
          return false;
        }
      });
    },
    async deleteOnclick(row, index) {
      const USBdata = {
        Data: {
          Name: row.Name
        }
      }
      await connrequest('CanDelUSBDevice', USBdata) //检查是否存在关联数据不能删除
      this.$confirm(`确定删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let arr = [...this.tableData]
        arr.splice(index, 1)
        const data = {
          Filter: {
            FileName: 'param_reg_usb.json'
          },
          Data: arr
        }
        const res = await connrequest('SetUICommonParam', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: `删除成功!`
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async putTableItemApi () {
      const index = this.editIndex
      const arr = [...this.tableData]

      arr[index] = { ...arr[index], ...this.auditForm }
      
      const res = await connrequest('SetUICommonParam', {
        Filter: {
          FileName: 'param_reg_usb.json'
        },
        Data: arr
      });

      if (res.Status.StatusCode === 0) {
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
        
        this.tableData = arr
        this.auditdialog = false;
      }
    },
    onFormClose () {
      this.editIndex = -1
      this.$refs['auditForm'].resetFields();
      this.auditForm = {}
    }
  }
}
</script>